<?php
/*
---------------------------------------------------------
														+
名称:易通支付通道										+
														+
控制器名称:YiTongController								+
														+
日期:2017-10-11											+
														+
作者:小翁												+
														+
---------------------------------------------------------
*/
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

class ShoufuController extends PayController{
    protected $config;
    protected $key;
    protected $url;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){
            case 1:
                $pay_bankcode = 'pay.wxpay.sm';
                break;
            //支付宝
            case 3:
            case 4:
            case 17:
            case 18:
                $pay_bankcode = 'pay.alipay.f2fpay';
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }


        $version='1.0';
        $merchant_id=$this->config['mch_id'];
        $out_trade_no=$return['orderid'];
        $total_amount=number_format($return['amount'],2,'.','');
        $service=$pay_bankcode;
        $nonce_str=time();
        $notify_url= $return['notifyurl'];
        $return_url=$return['callbackurl'];
        $goods_desc=strval(mt_rand(1,10000)).'支付';


        $sign=md5('charset=utf-8&goods_desc='.$goods_desc.'&merchant_id='.$merchant_id.'&nonce_str='.$nonce_str.'&notify_url='.$notify_url.'&out_trade_no='.$out_trade_no.'&return_url='.$return_url.'&service='.$service.'&sign_type=MD5&total_amount='.$total_amount.'&version=1.0&key='.$this->config['signkey']);

        $data = ['version'=>$version,'merchant_id'=>$merchant_id,'out_trade_no'=>$out_trade_no,'total_amount'=>$total_amount
            ,'service'=>$service,'notify_url'=>$notify_url,'return_url'=>$return_url,'goods_desc'=>$goods_desc,'nonce_str'=>$nonce_str,'sign_type'=>'MD5',
            'charset'=>'utf-8','sign'=>$sign
        ];

        $res = curl($this->config['gateway'], httpstr($data));//curl_post
        $resp = json_decode($res,true);

        //var_dump('<pre/>',$data,'返回数据：',$res,$resp);exit();


        $code = $resp['pay_info'];

        if(!$code){
            if($res['err_msg']){
                $this->showmessage($res['err_msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('未获取到支付链接!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        header("Location:{$code}");
    }

    //通知
    public function notifyurl(){
        //$this->debug_callback();
        if(!$this->checkip(getIP(),['47.99.173.124'])){
             exit("wrong");
        }
        $p = json_decode(file_get_contents('php://input'),true);

        if(!$p || empty($p)){
            exit("wrong");
        }

        foreach ($p as $k => $v){
            $p[$k] = htmlspecialchars($v);
        }


        //获取订单信息
        $orderid = $p['out_trade_no'];
        $find = $this->checkOrderNotify($orderid);

        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$p['busi_order_no']))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($p['transaction_id'])));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['sign'];

        $sign2 = strtoupper(md5( 'account='.$p['account'].'&charset='.$p['charset'].
            '&fee_type='.$p['fee_type'].
            '&merchant_id='.$p['merchant_id'].
            '&nonce_str='.$p['nonce_str'].
            '&out_trade_no='.$p['out_trade_no'].
            '&out_transaction_id='.$p['out_transaction_id'].
            '&pay_result='.$p['pay_result'].
            '&real_amount='.$p['real_amount'].
            '&real_pay_amount='.$p['real_pay_amount'].
            '&result_code='.$p['result_code'].
            '&sign_type='.$p['sign_type'].
            '&status='.$p['status'].
            '&time_end='.$p['time_end'].
            '&total_amount='.$p['total_amount'].
            '&trade_type='.$p['trade_type'].
            '&transaction_id='.$p['transaction_id'].
            '&version='.$p['version'].
            '&key='.$this->config['signkey']));

        if($sign !== $sign2){
            exit("sign_wrong");
        }
        if($p['status'] !== '0'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '支付成功'; exit;
    }
}